{% extends "app/base_site.html" %}

{% block title %} {% if  "add" == handle %}添加{% else %}编辑{% endif %}布控 {% endblock title %}

{% block stylesheets %}
  {{ block.super }}
    <style>
    .div_canvas_box{
        background: #e5e5e5;
        display: flex;
    }
    .div_canvas_box>video{
        width: 100%;
        height: 100%;
        /*object-fit: fill;*/
        /*border-radius: 5px;*/
        /*border: 1px solid #f0f0f0;*/
    }
    .div_canvas_box>video:focus {
        outline: -webkit-focus-ring-color auto 0px;
    }
    .div_canvas_box>canvas{
        margin: 0 0;
        border: 1px solid darkred;
        position: absolute;
        top: 0;
        left: 10px;
        /*width: 800px;*/
        /*height: 400px;*/
        z-index: 1;
    }
    .div_canvas_menu{
        margin-top: 50px;
        padding: 10px;
        border: 1px solid #e5e5e5;
        color: #ffffff;
        background-color: #ffffff;


    }

</style>

{% endblock stylesheets %}
{% block content %}

<script>
    let streamCodeDict = {};//视频流字典
    let streamCode;

    let algorithmCodeDict = {};//基础算法字典
    let algorithmCode;

    let audioCodeDict = {}; //音频字典
    let audioCode;

    let behaviourCodeDict = {}; //行为算法字典
    let behaviourCode;



</script>

  <div class="right_col" role="main">
    <div class="">

      <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
          <div class="x_panel">
            <div class="x_title">
              <h2>{% if  "add" == handle %}添加{% else %}编辑{% endif %}布控</h2>
              <div class="clearfix"></div>
            </div>
            <div class="x_content">

              <div class="col-md-8 col-sm-8 col-xs-12">
                  
                <div class="div_canvas_box">
                   <video id="video_player" controls autoplay>
                        Your browser is too old which doesn't support h5 video
                    </video>
                   <canvas id="canvas" width="0" height="0">
                        Your browser is too old which doesn't support h5 canvas
                    </canvas>
                </div>
                  <div class="div_canvas_menu">
                      <button id="play" type="button" class="btn btn-success btn-sm"><i class="fa fa-play"></i> 播放视频 </button>
                      <button id="stop" type="button" class="btn btn-default btn-sm"><i class="fa fa-stop"></i> 停止播放 </button>
                      <button id="btn_adjust" type="button" class="btn btn-default btn-sm"><i class="fa fa-adjust"></i> 识别区域与播放器对齐</button>
                      <button id="btn_clear" type="button" class="btn btn-default btn-sm"><i class="fa fa-paint-brush"></i> 清空算法识别区域</button>
                  </div>

              </div>

              <div class="col-md-4 col-sm-4 col-xs-12" >
                  <div class="form-horizontal form-label-left">

                        <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">布控编号</label>
                          <div class="col-md-9 col-sm-9 col-xs-12">
                              <span style="height: 34px;line-height: 34px;padding: 6px 0;">{{ control.code }}</span>
                          </div>
                        </div>

                    <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">选择视频流</label>
                        <div class="col-md-9 col-sm-9 col-xs-12">
                            {% if  "add" == handle %}
                              <select id="select_stream" class="select2_single form-control" required="required" >
                                  {% if streams|length == 0 %}
                                      <option value="-1">暂无视频流</option>
                                  {% else %}
                                      <option value="0">请选择视频流</option>

                                    {% for stream in streams %}
                                        <script>
                                            streamCode = '{{ stream.code }}';
                                            streamCodeDict[streamCode] = {
                                                'code':streamCode,
                                                "app":'{{ stream.app }}',
                                                "name":'{{ stream.name }}',
                                                "video":'{{ stream.video }}',
                                                "audio":'{{ stream.audio }}',
                                                "videoUrl":'{{ stream.videoUrl }}',
                                                "source_nickname":'{{ stream.source_nickname }}'
                                            }
                                        </script>
                                        <option value="{{ stream.code }}">{{ stream.source_nickname }}</option>
                                    {% endfor %}
                                  {% endif %}
                              </select>
                         {% else %}
                              <select id="select_stream"  disabled="disabled"  class="select2_single form-control" >
                              <!--streamCode的组成格式是 app_name -->
                                <option selected value="{{ control.stream_app }}_{{ control.stream_name }}">{{ control_stream_nickname}}</option>
                              </select>
                         {% endif %}
                       </div>
                   </div>


                    <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">视频信息</label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                             <input id="video"  type="text" disabled="disabled" value="{{ control.stream_video }}" class="form-control">
                      </div>
                    </div>

                    <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">音频信息</label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="audio"  type="text" disabled="disabled" value="{{ control.stream_audio }}" class="form-control">
                      </div>
                    </div>



                    <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">播放地址</label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="videoUrl"  type="url" disabled="disabled" value="{{ control_stream_videoUrl }}" class="form-control">
                      </div>
                    </div>

                          <div class="ln_solid"></div>


                    <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">选择算法
                          </label>

                          <div class="col-md-9 col-sm-9 col-xs-12">

                            <select id="select_algorithm"  class="select2_single form-control" required="required" >
                                <option value="0">请选择基础算法</option>
                                {% for algorithm in algorithms %}
                                   <script>
                                        algorithmCode = '{{ algorithm.code }}';
                                        algorithmCodeDict[algorithmCode] = {
                                            "code":algorithmCode,
                                            "name":'{{ algorithm.name }}',
                                            "way_code":'{{ algorithm.way_code }}',
                                            "model_class_names":'{{ algorithm.model_class_names }}'
                                        }

                                    </script>

                                    <option {% if algorithm.code == control.algorithm_code %} selected {% endif %} value="{{ algorithm.code }}">{{ algorithm.name }}</option>
                                {% endfor %}
                            </select>

                          </div>
                    </div>

                        <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">选择目标</label>
                          <div class="col-md-9 col-sm-9 col-xs-12">
                            <select id="select_class_name" {% if "API" == control_algorithm_way_code %}disabled="disabled"{% endif %}  class="select2_single form-control" required="required"  multiple="multiple" >
                                <option value="0">---请选择识别目标(可多选)---</option>
                            </select>
                          </div>
                        </div>
         <div class="ln_solid"></div>

                   <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">选择行为</label>
                          <div class="col-md-9 col-sm-9 col-xs-12">
                            <select id="select_behaviour" {% if "API" == control_algorithm_way_code %}disabled="disabled"{% endif %}   class="select2_single form-control" required="required" >
                                <option value="0">请选择行为算法</option>

                                {% for behaviour in behaviours %}
                                   <script>
                                        behaviourCode = '{{ behaviour.code }}';
                                        behaviourCodeDict[behaviourCode] = {
                                            "code":behaviourCode,
                                            "name":'{{ behaviour.name }}'
                                        }
                                    </script>

                                    <option {% if behaviour.code == control.behaviour_code %} selected {% endif %} value="{{ behaviour.code }}">{{ behaviour.name }}</option>
                                {% endfor %}

                            </select>
                          </div>
                        </div>

         <div class="ln_solid"></div>

                 <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12">选择音频 <i class="bxc_introduce fa fa-info-circle" title="触发报警时播放的音频"></i>
                          </label>

                          <div class="col-md-9 col-sm-9 col-xs-12">

                            <select id="select_audio"  class="select2_single form-control" required="required" >
                                <option value="0">请选择报警音频</option>
                                {% for audio in audios %}
                                   <script>
                                        audioCode = '{{ audio.code }}';

                                        audioCodeDict[audioCode] = {
                                            "code":audioCode,
                                            "name":'{{ audio.name }}'
                                        }

                                    </script>

                                    <option {% if audio.code == control.audio_code %} selected {% endif %} value="{{ audio.code }}">{{ audio.name }}</option>
                                {% endfor %}
                            </select>

                          </div>
                    </div>

                       <div class="form-group">
                           <label class="control-label col-md-3 col-sm-3 col-xs-12">是否推流 <i class="bxc_introduce fa fa-info-circle" title="实时分析视频时是否推流"></i></label>
                          <div class="col-md-9 col-sm-9 col-xs-12">

                            <div class="radio">
                              <label>
                                <input type="radio" {% if control.push_stream == 0 %} checked="checked" {% endif %} value="0" name="push_stream"> 算法处理的视频不推流
                              </label>
                            </div>

                            <div class="radio">
                              <label>
                                <input type="radio" {% if control.push_stream == 1 %} checked="checked" {% endif %} value="1" name="push_stream"> 算法处理的视频推流
                              </label>
                            </div>

                          </div>
                        </div>



                  <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">报警间隔 <i class="bxc_introduce fa fa-info-circle" title="1路视频最小报警间隔时长（单位秒）"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="min_interval"  type="number" value="{{ control.min_interval }}" class="form-control" >
                      </div>
                    </div>

                     <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">分类阈值 <i class="bxc_introduce fa fa-info-circle" title="目标被识别为指定分类的比例"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="class_thresh"  type="number" value="{{ control.class_thresh }}" class="form-control" >
                      </div>
                    </div>

                  <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">重叠阈值 <i class="bxc_introduce fa fa-info-circle" title="目标被检测的部分占目标本身的比例"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input id="overlap_thresh"  type="number" value="{{ control.overlap_thresh }}" class="form-control" >
                      </div>
                    </div>

                  <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">图片数量 <i class="bxc_introduce fa fa-info-circle" title="合成报警图片的数量"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                           <input name="alarm_image_count"  type="number" value="{{ control.alarm_image_count }}" class="form-control" >
                      </div>
                    </div>

                <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">画框选项 <i class="bxc_introduce fa fa-info-circle" title="合成报警视频画框类型"></i></label>
                      <div class="col-md-9 col-sm-9 col-xs-12">

                          <div class="radio">
                              <label>
                                <input type="radio" {% if control.alarm_draw_type == 0 %} checked="checked" {% endif %} value="0" name="alarm_draw_type"> 合成报警视频只保存画框
                              </label>
                            </div>

                            <div class="radio">
                              <label>
                                <input type="radio" {% if control.alarm_draw_type == 1 %} checked="checked" {% endif %} value="1" name="alarm_draw_type"> 合成报警视频同时保存画框和不画框
                              </label>
                            </div>


                      </div>
                    </div>

                         <div class="form-group">
                          <label class="control-label col-md-3 col-sm-3 col-xs-12" for="textarea">备注
                          </label>
                          <div class="col-md-9 col-sm-9 col-xs-12">
                            <textarea id="textarea_remark" required="required" name="textarea" class="form-control col-md-7 col-xs-12">{{ control.remark }}</textarea>

                          </div>
                        </div>


                        <div class="ln_solid"></div>
                        <div class="form-group">
                          <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
                            <button type="button" onclick="window.history.go(-1)" class="btn btn-primary">取消</button>
                            <button type="button" id="btn_submit" class="btn btn-success">提交</button>
                          </div>
                        </div>

                    </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
{% endblock content %}

{% block javascripts %}
  {{ block.super }}

<script src="/static/lib/wsPlayer/mp4box.all.min.js"></script>
<script src="/static/lib/wsPlayer/wsPlayer.js"></script>
<script>

    let controlCode= '{{ control.code }}';// 布控编号
    let old_control_polygon = '{{ control.polygon }}';// 布控多边形坐标点
    let old_control_algorithm_code = '{{ control.algorithm_code }}';// 布控原始基础算法编号
    let old_control_class_names = '{{ control.class_names }}';// 布控原始检测目标
    let old_control_stream_videoUrl = '{{ control_stream_videoUrl }}';// 已经布控的数据才存在该地址

    let handle = '{{ handle }}';// 操作类型 add 或 edit

    let eleCanvas=document.getElementById("canvas");
    let eleBtnAdjust = $("#btn_adjust");
    let eleBtnClear = $("#btn_clear");
    //得到画布的上下文,上下文有两个 2d和3d
    //所有的图形绘制都是通过ctx属性或者方法进行设置的，和canvas标签没有关系了
    let ctx = eleCanvas.getContext("2d");
    let recognitionRegionLineArray = [];//存储多边形的每一条边
    let recognitionRegionLineMaxCount = 4;//多边形的边数
    let tempPolygonLine = null;//多边形的边，临时变量

    let player = null;
    let eleVideoPlayer= document.getElementById("video_player");
    let eleSelectStream = $("#select_stream");// select  选择视频流
    let eleVideoUrl= $("#videoUrl");// input
    let eleVideo = $("#video");// input
    let eleAudio = $("#audio");// input
    let eleBtnPlay = $("#play");//button
    let eleBtnStop = $("#stop");//button

    let eleSelectAlgorithm = $("#select_algorithm");// select 基础算法
    let selected_algorithm_way_code = "";

    let eleSelectClassName = $("#select_class_name");// select 布控多选的目标
    let eleSelectAudio = $("#select_audio");// select 音频
    let eleSelectBehaviour = $("#select_behaviour");// select 行为算法
    let eleInputMinInterval = $("#min_interval");
    let eleInputClassThresh = $("#class_thresh");
    let eleInputOverlapThresh = $("#overlap_thresh");

    //是否推流
    let eleRadioPushStream = $('input[type=radio][name=push_stream]');//radio
    let pushStream = $('input[type=radio][name=push_stream]:checked').val();

    // 报警合成图片数量
    let eleInputAlarmImageCount= $("input[type=number][name='alarm_image_count']");
    // 报警视频是否画框
    let eleRadioAlarmDrawType = $('input[type=radio][name=alarm_draw_type]');//radio
    let alarmDrawType = $('input[type=radio][name=alarm_draw_type]:checked').val();

    let eleTextareaRemark = $("#textarea_remark");// textarea remark

    let eleBtnSubmit = $("#btn_submit");//添加或更新布控数据

    class MyPoint{
        constructor(x,y) {
            this.x = x;
            this.y = y;
        }
    }
    //创建线段类  多个线段对象相互连接就成为了点
    class MyLine{
        x2;
        y2;
        //构造方法设置第一个点
        constructor(x,y) {
          this.x=x;
          this.y=y;
        }
        //更新 设置第二给点
        LineUpdate=function (x,y){
          this.x2=x;
          this.y2=y;
        }


        //绘制
        LineDraw=function (){
            ctx.lineWidth = 2;//设置线条宽度
            //ctx.font = "normal bold 40px Arial";//设置字体
            ctx.strokeStyle="red" //设置颜色

          ctx.beginPath();
          ctx.moveTo(this.x,this.y);//第一个点
          ctx.lineTo(this.x2,this.y2); //点三个
          ctx.stroke(); //开始绘制(把前面点连接)
        }

    }

    //清空绘制区域数据
    function f_clearVideoCanvas() {
        ctx.clearRect(0,0,eleCanvas.width,eleCanvas.height);
        recognitionRegionLineArray = [];

    }
    //窗口对齐->清空绘制区域数据
    function f_adjustVideoCanvas() {
        //执行窗口对齐以后，此前的绘制区域数据，可能不在对应，因此需要删除
        let w = eleVideoPlayer.offsetWidth;
        let h = eleVideoPlayer.offsetHeight;
        console.log("f_adjustVideoCanvas",w,h)
        w = w - 1.8;
        h = h - 2.2;
        eleCanvas.setAttribute("width",String(w));
        eleCanvas.setAttribute("height",String(h));
        f_clearVideoCanvas();
    }
    function f_reDrawVideoCanvas() {
        console.log("f_reDrawVideoCanvas() recognitionRegionLineArray.length=",recognitionRegionLineArray.length);
        ctx.clearRect(0,0,eleCanvas.width,eleCanvas.height);
        for (let i = 0; i < recognitionRegionLineArray.length; i++) {
            let line = recognitionRegionLineArray[i];
            line.LineDraw();
        }
    }
    //画布鼠标监听 按下  按下后绘制图形
    eleCanvas.addEventListener("mousedown",function (event){
        if(recognitionRegionLineArray.length < recognitionRegionLineMaxCount){
            if(tempPolygonLine===null){
                let x = event.offsetX;
                let y = event.offsetY;
                tempPolygonLine=new MyLine(x,y);
            }
        }
    });
    // 获取鼠标在画布移动的坐标
    eleCanvas.addEventListener("mousemove", function(event){
        if(tempPolygonLine){
            let x = event.offsetX;
            let y = event.offsetY;

            f_reDrawVideoCanvas();
            tempPolygonLine.LineUpdate(x,y);
            tempPolygonLine.LineDraw();
        }


    });
    //鼠标左键弹起时候
    eleCanvas.addEventListener("mouseup",function (event){
        if(tempPolygonLine){

            f_reDrawVideoCanvas();
            let x = event.offsetX;
            let y = event.offsetY;
            if(recognitionRegionLineArray.length === recognitionRegionLineMaxCount-1){//还差一条边的时候，将第一条边的起点作为最后一条边的终点
                let firstLine = recognitionRegionLineArray[0];
                x = firstLine.x;
                y = firstLine.y;
            }
            tempPolygonLine.LineUpdate(x,y);
            tempPolygonLine.LineDraw();
            recognitionRegionLineArray.push(tempPolygonLine);

            console.log("mouseup() recognitionRegionLineArray.length=",recognitionRegionLineArray.length);
            if(recognitionRegionLineArray.length < recognitionRegionLineMaxCount){
                tempPolygonLine=new MyLine(x,y);
            }else{
                tempPolygonLine=null;
            }
        }
    })
    //绘制区域与视频窗口对齐
    eleBtnAdjust.click(function () {
        f_adjustVideoCanvas();
    })
    eleBtnClear.click(function () {
        f_clearVideoCanvas();
    })
    function f_showSettings(algorithm_code,selected_class_names) {

        let html = "<option value=\"0\">---请选择识别目标(可多选)---</option>";
   
        let algorithm = algorithmCodeDict[algorithm_code];
        selected_algorithm_way_code = algorithm["way_code"];

        if("MODEL" === selected_algorithm_way_code){
            //需要显示选择目标
            eleSelectClassName.removeAttr("disabled");
            let model_class_names = algorithm["model_class_names"];
            let model_class_names_array = model_class_names.split(",");
            let selected_class_names_array = selected_class_names.split(",");
            for (let i = 0; i < model_class_names_array.length; i++) {
                let class_name = model_class_names_array[i];
                let match = selected_class_names_array.indexOf(class_name);
                if(match > -1){
                    html += "<option selected value=\""+class_name+"\">"+class_name+"</option>";
                }else{
                    html += "<option value=\""+class_name+"\">"+class_name+"</option>";
                }
            }
            //需要使用行为算法
            eleSelectBehaviour.removeAttr("disabled");
        }else if("API" === selected_algorithm_way_code){
            //不需要显示选择目标
            eleSelectClassName.attr("disabled","disabled");
            //不需要使用行为算法
            eleSelectBehaviour.attr("disabled","disabled");
            eleSelectBehaviour.val("0")

        }else{
            //预留



        }

        eleSelectClassName.html(html);
    }
    eleSelectStream.change(function () {
        streamCode = $(this).val();
        let stream = streamCodeDict[streamCode];
        if (stream) {
            let videoUrl = stream["videoUrl"]
            eleVideoUrl.val(videoUrl)
            eleVideo.val(stream["video"])
            eleAudio.val(stream["audio"])
            f_playStart(videoUrl);
        }else{
            eleVideoUrl.val("")
            eleVideo.val("")
            eleAudio.val("")
            f_playStop();
        }

        for (let i = 0; i < 10; i++) {
            setTimeout(function () {
                f_adjustVideoCanvas();
            }, i*200);
        }

    });
    eleSelectAlgorithm.change(function () {
        let algorithm_code = $(this).val();
        if(algorithm_code === old_control_algorithm_code){
             f_showSettings(algorithm_code,old_control_class_names);
        }else{
             f_showSettings(algorithm_code,"");
        }

    });
    eleBtnPlay.click(function () {
        f_playStart(eleVideoUrl.val());
    });
    eleBtnStop.click(function (){
        f_playStop();
    });

    eleRadioPushStream.change(function () {
        pushStream = $(this).val();
    });
    eleRadioAlarmDrawType.change(function () {
       alarmDrawType = $(this).val();
    });

    window.onresize = function () {
        f_adjustVideoCanvas();
    }
    function f_playStart(videoUrl){
        console.log(videoUrl);
        if(typeof videoUrl === "undefined" || !videoUrl.endsWith(".mp4")){
            myAlert("视频流地址格式不正确！","error");
            return;
        }
	    player = new wsPlayer("video_player", videoUrl);
        player.open();
    }
    function f_playStop(){
        if(player){
            player.close();
            player = null;
        }else{
            myAlert("播放器未启动！","error");
        }

    }
    eleBtnSubmit.click(function () {// 添加布控数据 或 更新布控数据
        f_postHandleControl();
    });
    function f_postHandleControl() {
        streamCode = eleSelectStream.val().trim();//typeof string
        if(streamCode==="-1"){
            myAlert("暂无视频流","error");
            return;
        }else if(streamCode==="0"){
            myAlert("请选择视频流","error");
            return;
        }
        algorithmCode = eleSelectAlgorithm.val().trim();//typeof string
        if(algorithmCode==="0"){
            myAlert("请选择基础算法","error");
            return;
        }
        let p_classNames = ""; //选择目标判断 person,dog,cat,,,
        let p_behaviourCode = "";
        if("MODEL" === selected_algorithm_way_code){
            //选择目标判断
            let classNames_array = eleSelectClassName.val();//typeof object, array
            if(classNames_array===null){
                myAlert("请选择至少1个目标","error");
                return;
            }else{
                let classNames_array2 = [];
                for (let i = 0; i < classNames_array.length; i++) {
                    if("0"!==classNames_array[i]){
                        classNames_array2.push(classNames_array[i]);
                    }
                }
                if(classNames_array2.length > 0){
                    p_classNames = classNames_array2.join(",");
                }else{
                    myAlert("请选择至少1个目标","error");
                    return;
                }
            }
            //行为算法判断
            p_behaviourCode = eleSelectBehaviour.val().trim();//typeof string
            if(p_behaviourCode==="0"){
                myAlert("请选择行为算法","error");
                return;
            }
        }else if("API" === selected_algorithm_way_code){
            //不需要选择目标&行为算法


        }else{
            //预留

        }

        audioCode = eleSelectAudio.val().trim();//typeof string
        if(audioCode==="0"){
            myAlert("请选择音频","error");
            return;
        }

        let minInterval = parseInt(eleInputMinInterval.val());
        if(isNaN(minInterval)){
            myAlert("报警间隔时间不能为空","error");
            return;
        }
        if(minInterval<0){
            myAlert("报警间隔时间不能小于0秒","error");
            return;
        }

        let classThresh = parseFloat(eleInputClassThresh.val());
        if(isNaN(classThresh)){
            myAlert("分类阈值不能为空","error");
            return;
        }
        if(classThresh<=0){
            myAlert("分类阈值不能小于等于0","error");
            return;
        }
        if(classThresh>1){
            myAlert("分类阈值不能大于1","error");
            return;
        }

        let overlapThresh = parseFloat(eleInputOverlapThresh.val());
        if(isNaN(overlapThresh)){
            myAlert("重叠阈值不能为空","error");
            return;
        }

        if(overlapThresh<=0){
            myAlert("重叠阈值不能小于等于0","error");
            return;
        }
        if(overlapThresh>1){
            myAlert("重叠阈值不能大于1","error");
            return;
        }
        //报警合成图片数量start
        let alarmImageCount = parseInt(eleInputAlarmImageCount.val());
        if(isNaN(alarmImageCount)){
            myAlert("报警合成图片数量不能为空","error");
            return;
        }
        if(alarmImageCount<=0){
            myAlert("报警合成图片数量不能小于等于0","error");
            return;
        }
        if(alarmImageCount>50){
            myAlert("报警合成图片数量不能大于50","error");
            return;
        }
         //报警合成图片数量end

        let remark = eleTextareaRemark.val().trim();
        console.log("recognitionRegionLineArray=",recognitionRegionLineArray)

        let __polygon_point_array = [];// x1,y1,x2,y2,x3,y3,x4,y4 ->顺时针
        if(recognitionRegionLineArray.length === 0){
            __polygon_point_array.push(0);
            __polygon_point_array.push(0);

            __polygon_point_array.push(1);
            __polygon_point_array.push(0);

            __polygon_point_array.push(1);
            __polygon_point_array.push(1);

            __polygon_point_array.push(0);
            __polygon_point_array.push(1);

        }else{
            if(recognitionRegionLineArray.length!==recognitionRegionLineMaxCount){
                myAlert("绘制算法识别区域需要形成闭环！","error");
                return;
            }
            let canvas_width = eleCanvas.width;
            let canvas_height = eleCanvas.height
            for (let i = 0; i < recognitionRegionLineArray.length; i++) {
                let line = recognitionRegionLineArray[i];
                __polygon_point_array.push((line.x/canvas_width).toFixed(4));
                __polygon_point_array.push((line.y/canvas_height).toFixed(4));
            }
        }


        console.log("__polygon_point_array=",__polygon_point_array)

        let polygon = __polygon_point_array.join(",");

        let data = {
            "controlCode":controlCode,
            "algorithmCode":algorithmCode,
            "classNames":p_classNames,
            "behaviourCode":p_behaviourCode,
            "audioCode":audioCode,
            "pushStream":pushStream,
            "polygon":polygon,
            "minInterval":minInterval,
            "classThresh":classThresh,
            "overlapThresh":overlapThresh,
            "alarmDrawType":alarmDrawType,
            "alarmImageCount":alarmImageCount,
            "remark":remark
        }

        let handleUrl;
        if("add" === handle){
            handleUrl = "/control/postAdd";
            let stream = streamCodeDict[streamCode];
            if (stream){
                data["streamApp"] = stream["app"]
                data["streamName"] = stream["name"]
                data["streamVideo"] = stream["video"]
                data["streamAudio"] = stream["audio"]
            }else{
                return;
            }
        }else if("edit" === handle){
            handleUrl = "/control/postEdit";
        }else{
            return;
        }


        $.ajax({
           url: handleUrl,
           type: "post",
           async: true,
           data: data,
           dataType: "json",
           timeout: "3000",
           error: function () {
                myAlert("网络异常，请确定网络正常！","error");
           },
           success: function (res) {
               if(1000 === res.code){
                    myAlert(res.msg,"success");
               }else{
                    myAlert(res.msg,"error");
               }
           }
        });

    }
    window.onload = function () {
        if(old_control_stream_videoUrl!==""){
            //编辑布控
            f_showSettings(old_control_algorithm_code,old_control_class_names);
            f_playStart(old_control_stream_videoUrl);
        }else{
            //新增布控
            f_adjustVideoCanvas();
        }

        setTimeout(function () {
            if(old_control_polygon!==""){//编辑布控->绘制周界区域存在
                 f_adjustVideoCanvas();
                let xys = old_control_polygon.split(",");
                let lineCount = xys.length / 2;
                if(lineCount >= 3){
                    let points = [];
                    let canvas_width = eleCanvas.width;
                    let canvas_height = eleCanvas.height
                    for (let i = 0; i < lineCount; i++) {
                        let x_index = i * 2;
                        let y_index = x_index+1;
                        let x = parseInt(parseFloat(xys[x_index]) * canvas_width);
                        let y = parseInt(parseFloat(xys[y_index]) * canvas_height);
                        let p = new MyPoint(x,y);
                        points.push(p);
                    }
                    for (let i = 0; i < lineCount; i++) {
                        let p1 = points[i];
                        let p2;
                        if(i===(lineCount-1)){
                            p2 = points[0];
                        }else{
                            p2 = points[i+1];
                        }
                        let line = new MyLine(p1.x,p1.y);
                        line.LineUpdate(p2.x,p2.y);
                        recognitionRegionLineArray.push(line);
                    }

                }
                f_reDrawVideoCanvas();
            }
        }, 1200);

    }
</script>

{% endblock javascripts %}
